﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data;

namespace DAL
{
    public class sqlHelper
    {
        private static MySqlConnection CreateConnection()
        {
            MySqlConnection con = new MySqlConnection();
            con.ConnectionString= @"server=localhost;
                                     port=3306;
                                     database=parkinglotbill;
                                     user=qcl;
                                     password=qcl123;
                                     charset=utf8";
            return con;
        }

        public static int ExcuteNonquery(string sql, MySqlParameter[] parameters)
        {
            MySqlCommand cmd = new MySqlCommand();
            int result = 0;
            try
            {
                cmd.Connection = CreateConnection();
                cmd.CommandText = sql;
                cmd.Connection.Open();
                if (parameters != null)
                    cmd.Parameters.AddRange(parameters);
                result = cmd.ExecuteNonQuery();
            }
            catch 
            { }
            finally
            {
                cmd.Connection.Close();
            }
            return result;
        }

        public static DateTime OutCar(string sql, MySqlParameter[] parameters)
        {
            DateTime result=DateTime.Now;
            //第二步 新建一个用于执行sql语句的命令对象
            MySqlCommand cmd = new MySqlCommand();
            //这里使用try{}catch{}语块来对数据库连接等异常作出反应提示
            try
            {
                cmd.Connection = CreateConnection();//制定命令对象所用的连接
                cmd.Connection.Open();
                cmd.CommandText = sql;
                if (parameters != null)
                    cmd.Parameters.AddRange(parameters);//添加sql参数数据到cmd对象的parameters集合中
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result = Convert.ToDateTime(dr["StartTime"]);
                }
            }
            catch
            {
            }
            finally
            {
                //第四步 使用完连接对象后关闭连接
                cmd.Connection.Close();
            }
            return result;
        }
    }
}
